/*  
 * cafe-nCharts.js
 * @Author :      CHENPEIPEI
 * @CreateDate :  2017年6月9日
 * Copyright (c) 2017, NRIET.　
 * TODO
 * 		highcharts二次封装
 */

;define(function(){
	//监听div宽高对应
	$.fn.resize = function(callback){
		$(this).each(function(){
			var resizeDom = this;
			resizeDom.callback = callback;
			if(this == window){
				window.onresize = function(){
					resizeDom.callback();
				}
			}else{
				$(this).divResize(callback);
			}
		})
	};
	
	$.fn.divResize = function(callback){
		var cycleTime = 250;
		if(callback == undefined || callback == null){
			return;
		}
		if(!typeof callback == "function"){
			return;
		}
		$(this).each(function(){
			var resizeDom = this;
			resizeDom.data = {};
			resizeDom.data.width = $(resizeDom).css("width");
			resizeDom.data.height = $(resizeDom).css("height");
			resizeDom.callback = callback;
			var resizeMonitor = function(){
				if($(resizeDom).css("width") != resizeDom.data.width || $(resizeDom).css("height") != resizeDom.data.height){
					resizeDom.data.width = $(resizeDom).css("width");
					resizeDom.data.height = $(resizeDom).css("height");
					resizeDom.callback();
				}
				var callFunc = arguments.callee;
				setTimeout(function(){
					callFunc();
				},cycleTime)
			};
			resizeMonitor();
		})
	}
	
	//类型对应的数据
	var elementTypeData =[{elementType : 'TP',type : 'column',unit : '（mm）',min : 0},//降水
	                     {elementType : 'TMP',type : 'spline',unit : '（℃）'},//气温
	                     {elementType : 'RH',type : 'spline',unit : '（%）',min : 0,max : 100},//湿度
	                     {elementType : 'EDA',type : 'spline',unit : '（m/s）',min : 0},//风速风向
	                     {elementType : 'TCC',type : 'column',unit : '（成）',min : 0,max : 10},//云量
	                     {elementType : 'VIS',type : 'spline',unit : '（km）',min : 0},//能见度
	                     {elementType : 'GUST',type : 'spline',unit : '（m/s）',min : 0},//阵风
	                     {elementType : 'QXAQI',type : 'areaspline',unit : '',min : 0}, //气象研判污染指标-AQI
	                     {elementType : 'QXPOLL',type : 'areaspline',unit : '(μg/m³)',min : 0}, //气象研判污染指标PM2.5、PM10、SO2、NO2、O3、O3_8
	                     {elementType : 'QXCO',type : 'areaspline',unit : '(mg/m³)',min : 0}, //气象研判污染指标CO
	                     {elementType : 'QXTMP',type : 'areaspline',unit : '（℃）'},
	                     {elementType : 'QXRH',type : 'areaspline',unit : '（%）',min : 0,max : 100},
	                     {elementType : 'UR',type : 'areaspline',unit : '',min : 0,max : 15}, //紫外线
	                     {elementType : 'maiAQI',type : 'column',unit : '',min : 0},
	                     {elementType : 'AIRAQI',type : 'column',unit : '',min : 0},
	                     {elementType : 'AIRPOLL',type : 'spline',unit : '(ug/m³)',min : 0},
	                     {elementType : 'AIRCO',type : 'spline',unit : '(mg/m³)',min : 0},
	                     {elementType : 'whyjAQI',type : 'areaspline',unit : '',min : 0},
	                     {elementType : 'ksybAQI',type : 'areaspline',unit : '',min : 0},
	                     {elementType : 'zhfxAQI',type : 'areaspline',unit : '',min : 0},
						 {elementType : 'AQI',type : 'spline',unit : '',min : 0},//AQI预报
						 {elementType : 'UV',type : 'spline',unit : '(W/M²)',min : 0},// 紫外线强度
						 {elementType : 'PRE',type : 'spline',unit : '（hPa）',min : 0},//气压
						 {elementType : 'SNOW',type : 'spline',unit : '（cm）',min : 0},//雪
						 {elementType : 'VISIB',type : 'spline',unit : '（m）',min : 0}//能见度(单位m)
						 ];
	
	var highstockdefault = {
			series:{
				marker : {
					enabled:true,
					radius : 4
				}
			}
	}
	var showLabelData = {}; //记录当前的数据列以及需要在线上显示数据的记录
	var chartObj = {};
	//画highcharts图表
	function initChart(settings){
		
		CFnCharts.defaults = $.extend(CFnCharts.defaults,settings);
		CFnCharts.defaults.chartstyle.renderTo = settings.containId;
		
		var day ="01";
		var firstHour = "";
		if(settings.modelType == "AQI" || settings.modelType == "QX" || settings.modelType == "mai" 
			|| settings.modelType == "aq-AQI" || settings.modelType == "whyj-AQI" || settings.modelType == "whyj-AQIHS" || 
			settings.modelType == "ZHFX" || settings.modelType == "timeSequence"){
			//获得一天开始的小时是哪一个，方便下面显示天
			/*$.each(settings.catagory,function(index,item){
				day = item;
			});*/
		}
		else{
			//获得一天开始的小时是哪一个，方便下面显示天
			$.each(settings.catagory,function(index,item){
				if(index == 0){
					day = new Date(item).getDate();
				}else{
					if(new Date(item).getDate()!= day){
						firstHour = new Date(item).getHours();
						day = new Date(item).getDate();
					}
				}
			});
		}
		var flag = false;
		var titleJson = {
				align :'high',
				margin : -35,
				text: CFnCharts.defaults.xText,
				style : {
					color : '#7CAEEE',
					fontWeight : 'bold'
				}
			};
		if(settings.modelType == "AQI" || settings.modelType == "QX" || settings.modelType == "YB"
			|| settings.modelType == "mai" || settings.modelType == "aq-AQI"|| settings.modelType == "timeSequence"){
			CFnCharts.defaults.xText = "";
			flag = true;
			titleJson = {
					align :'high',
					offset: 0,
					y:5,
					x:5,
					text: CFnCharts.defaults.xText,
					style : {
						color : '#7CAEEE',
						fontWeight : 'bold'
					}
				};
		}else if(settings.modelType == "whyj-AQI"|| settings.modelType == "whyj-AQIHS" || settings.modelType == "ZHFX"){
			CFnCharts.defaults.xText = "(h)";
			flag = true;
			titleJson = {
					align :'high',
					offset: 0,
					y:5,
					x:5,
					text: CFnCharts.defaults.xText,
					style : {
						color : '#7CAEEE',
						fontWeight : 'bold'
					}
				};
		}
		//同时显示x轴最后一个刻度值和日期时间标签
		if(settings.showLastAndTip && settings.showLastAndTip == 1){
			flag = true
		}
		var options = {
				chart: CFnCharts.defaults.chartstyle,
		        credits :{
					enabled : false,
				},
				rangeSelector:{
					enabled:false,
				},
				legend : {
						enabled: true,
						floating: true,
						align : 'left',
						verticalAlign : "top"
				},
				scrollbar: {
		        	enabled : false,
		        },
				xAxis :{
					showFirstLabel :true,
					showLastLabel : flag,
					title : titleJson,
					labels : {
						useHTML : true,
						formatter : function(){
							if(settings.modelType == "AQI" || settings.modelType == "QX"|| settings.modelType == "mai"|| settings.modelType == "timeSequence"){
								return this.value;
							}else if(settings.modelType == "YB"){
								var data = new Date(this.value);
								var hour = (data.getHours() < 10 ? "0" : "")+data.getHours();
								var day = (data.getDate() < 10 ? "0" : "")+data.getDate();
								if(hour == "02"){
									return hour+"<br>"+"<span style='color:#C17C41;font-size:12px;'>"+day+"日</span>";
								}else{
									return hour;
								}
							}else if(settings.modelType == "aq-AQI"){
								return this.value;
							}else if(settings.modelType == "whyj-AQI"|| settings.modelType == "whyj-AQIHS" || settings.modelType == "ZHFX"){
								var data = this.value.split("<br>");
								if(data[0] == "00"){
									return data[0]+"<br>"+"<span style='color:#D5A669;font-size:12px;'>"+data[1]+"日</span>";
								}else{
									return data[0];
								}
							}
							else{
								firstHour = "08";
								var data = new Date(this.value);
								var minute = (data.getMinutes() < 10 ? "0" : "")+data.getMinutes();
								var hour = (data.getHours() < 10 ? "0" : "")+data.getHours();
								var day = (data.getDate() < 10 ? "0" : "")+data.getDate();
								if(this.isFirst || firstHour == hour){
									if(settings.noHour && settings.noHour == 1 && settings.xLineMin != 1){
										return "<span style='color:#C17C41;font-size:12px;'>"+day+"日</span>";
									}else if(settings.xLineMin == 1){
										return minute+"<br>"+"<span style='color:#C17C41;font-size:12px;'>"+hour+"时</span>";
									}else{
										return hour+"<br>"+"<span style='color:#C17C41;font-size:12px;'>"+day+"日</span>";
									}
								}else{
									if(settings.xLineMin == 1){
										if(minute == "00"){
											return minute+"<br>"+"<span style='color:#C17C41;font-size:12px;'>"+hour+"时</span>";
										}else{
											return minute;
										}
									}else{
										return hour;
									}
								}
							}
						}
					}
				},
		        tooltip : {
		        	//animation : false,
		        	 crosshairs : false,
		        	 shared: true ,
		        	 backgroundColor:'#578bed',
		        	 borderColor:'#fff',
		        	 borderWidth:1,
		        	 style : {
		        		 color:'#ffffff'
		        	 },
		        	 formatter : function(){
		        		 console.log("settings.modelType",settings,settings.modelType)
		        		 var html = '<table>';
		        		 if(settings.modelType == "AQI"){
		        			 var data = this.x;
		        			 if(settings.modelTitle != undefined){
		        				 html += '<tr><td colspan = "3">'+settings.modelTitle+'</td></tr><br>';
		        				 html += '<tr><td colspan = "2" style="color:#E0E0E8;">'+data.substring(0,4)+"年"+data.substring(5,7)+"月"+data.substring(8)+'日</td><td></td></tr><br>';
			        			 $.each(this.points,function(index,item){
				        			 var index = Number(item.series.index)+1;
				        			 if(item.y != -1){
				        				 html +='<tr><td>'+index+"、"+item.series.name+':</td><td>'+item.y+'</td><td></td></tr><br>';
				        			 }
				        		 });
		        			 }else{
		        				 html += '<tr><td colspan = "2" style="color:#E0E0E8;">'+data.substring(0,4)+"年"+data.substring(5,7)+"月"+data.substring(8)+'日</td><td></td></tr><br>';
			        			 $.each(this.points,function(index,item){
				        			 var index = Number(item.series.index)+1;
				        			 if(item.y != -1){
				        				 html +='<tr><td>'+item.series.name+':</td><td>'+item.y+'</td><td></td></tr><br>';
				        			 }
				        		 });
		        			 }
		        		 }else if(settings.modelType == "QX"){
		        			 var data = this.x;
		        			 html += '<tr><td colspan = "3">'+$(".wf-area select option:selected").text()+'</td></tr><br>';
		        			 if(data.indexOf("时")  < 0 ){
		        				 html += '<tr><td colspan = "2" style="color:#E0E0E8;">'+data.replace("-","月")+'日</td><td></td></tr><br>';
		        			 }else{
		        				 html += '<tr><td colspan = "2" style="color:#E0E0E8;">'+data+'</td><td></td></tr><br>';
		        			 }
		        			 $.each(this.points,function(index,item){
			        			 var index = Number(item.series.index)+1;
			        			 if(item.y != -1){
			        				 html +='<tr><td>'+item.series.name+':</td><td>'+item.y+'</td><td></td></tr><br>';
			        			 }
			        		 });
		        		 }else if(settings.modelType == "mai"){
		        			 var data = this.x;
		        			 html += '<tr><td colspan = "3">'+$("#wf-maiSelect option:selected").text()+'</td></tr><br>';
		        			 html += '<tr><td colspan = "2" style="color:#E0E0E8;">'+data.substring(0,4)+"-"+data.substring(4,6)+"-"+data.substring(6)+'</td><td></td></tr><br>';
		        			 $.each(this.points,function(index,item){
			        			 var index = Number(item.series.index)+1;
			        			 html +='<tr><td>'+item.series.name+':</td><td>'+item.y+'</td><td></td></tr><br>';
			        		 });
		        		 }else if(settings.modelType == "aq-AQI"){
		        			 var data = this.x;
		        			 if(data.indexOf("月") != -1 && data.indexOf("日") != -1){
		        				 html += '<tr><td colspan = "2" style="color:#E0E0E8;">'+data+'</td><td></td></tr><br>';
		        			 }else{
			        			 if(data.toString().split("<br>")[1] == undefined){
			        				 html += '<tr><td colspan = "2" style="color:#E0E0E8;">'+data+"时"+'</td><td></td></tr><br>';
			        			 }else{
			        				 html += '<tr><td colspan = "2" style="color:#E0E0E8;">'+data.toString().split("<br>")[1].replace("-","月")+"日 "+data.toString().split("<br>")[0]+"时"+'</td><td></td></tr><br>';
			        			 }
		        			 }
		        			 if(settings.firstPoll != undefined && settings.aqiLevel != undefined){
		        				 $.each(this.points,function(index,item){
				        			 var index = Number(item.series.index)+1;
				        			 html +='<tr><td>'+item.series.name+':</td><td>'+item.y+'</td><td></td></tr><br>';
				        			 html +='<tr><td>首要污染物:</td><td>'+settings.firstPoll[index-1]+'</td><td></td></tr><br>';
				        			 html +='<tr><td>等级:</td><td>'+settings.aqiLevel[index-1]+'</td><td></td></tr><br>';
				        		 });
		        			 }else{
		        				 $.each(this.points,function(index,item){
				        			 var index = Number(item.series.index)+1;
				        			 if(item.series.name == "CO"){
				        				 html +='<tr><td>'+item.series.name+':</td><td>'+item.y+'mg/m³</td><td></td></tr><br>';
				        			 }else{
				        				 html +='<tr><td>'+item.series.name+':</td><td>'+item.y+'μg/m³</td><td></td></tr><br>';
				        			 }
				        		 });
		        			 }
		        		 }else if(settings.modelType == "timeSequence"){
								var tipMessage = this.points[0].x.split("<br/>");
								tipMessage = "时间"+" : "+tipMessage[0]+"<br/>";
								for ( var i = 0; i < this.points.length; i++) {
									var name = this.points[i].series.name;
									var unit = "μg/m³";
									if(name == "CO"){
										 unit = "mg/m³";
									}
									if(name == "AQI"){
										unit = "";
									}
									if(name == "降水量"){
										unit = "mm";
									}
									if(name.indexOf("温度") >-1 || name.indexOf("气温") >-1){
										unit = "℃";
									}
									if(name == "风速风向"){
										unit = "m/s";
									}
									var yval = this.points[i].y;
									tipMessage = tipMessage
											+name + " : "
											+ yval + ""+unit; 
									tipMessage = tipMessage + "<br/>";
									
								}
								return tipMessage;
							}else if(settings.modelType == "EDA"){
								var data =  new Date(this.x);
			        			 if(CFnCharts.defaults.modpSeries[0].timemodel && CFnCharts.defaults.modpSeries[0].timemodel == "mm"){
			        				 var time = (data.getMonth()+1)+" 月 "+data.getDate()+" 日 "+data.getHours()+" 时 "+data.getMinutes()+" 分";
			        			 }else if(CFnCharts.defaults.modpSeries[0].timemodel && CFnCharts.defaults.modpSeries[0].timemodel == "dd"){
			        				 var time = (data.getMonth()+1)+" 月 "+data.getDate()+" 日 ";
			        			 }else{
			        				 var time = (data.getMonth()+1)+" 月 "+data.getDate()+" 日 "+data.getHours()+" 时 ";
			        			 }
				        		 html += '<tr><td colspan = "3">'+time+'</td></tr><br>';
				        		 $.each(this.points,function(index,item){
				        			 var index = Number(item.series.index)+1;
				        			 if(settings.dunhao && settings.dunhao == 1){
				        				 html +='<tr><td>'+'</td><td>'+item.series.name+':</td><td>'+item.y+this.series.tooltipOptions.valueSuffix+' 风向：' + item.point.direction +'</td></tr><br>';
				        			 }else{
				        				 html +='<tr><td>'+index+'、</td><td>'+item.series.name+':</td><td>'+item.y+this.series.tooltipOptions.valueSuffix+' 风向：' + item.point.direction +'</td></tr><br>';
				        			 } 
				        		 }); 
							}else{
		        			 var data =  new Date(this.x);
//		        			 console.log('elementTypeDatass',CFnCharts.defaults.modpSeries[0].timemodel)
		        			 if(CFnCharts.defaults.modpSeries[0].timemodel && CFnCharts.defaults.modpSeries[0].timemodel == "mm"){
		        				 var time = (data.getMonth()+1)+" 月 "+data.getDate()+" 日 "+data.getHours()+" 时 "+data.getMinutes()+" 分";
		        			 }else if(CFnCharts.defaults.modpSeries[0].timemodel && CFnCharts.defaults.modpSeries[0].timemodel == "dd"){
		        				 var time = (data.getMonth()+1)+" 月 "+data.getDate()+" 日 ";
		        			 }else{
		        				 var time = (data.getMonth()+1)+" 月 "+data.getDate()+" 日 "+data.getHours()+" 时 ";
		        			 }
			        		 html += '<tr><td colspan = "3">'+time+'</td></tr><br>';
			        		 $.each(this.points,function(index,item){
			        			 var index = Number(item.series.index)+1;
			        			 if(settings.dunhao && settings.dunhao == 1){
			        				 html +='<tr><td>'+'</td><td>'+item.series.name+':</td><td>'+item.y+this.series.tooltipOptions.valueSuffix+'</td></tr><br>';
			        			 }else{
			        				 html +='<tr><td>'+index+'、</td><td>'+item.series.name+':</td><td>'+item.y+this.series.tooltipOptions.valueSuffix+'</td></tr><br>';
			        			 } 
			        		 }); 
		        		 }
		        		 html += '</table>';
		        		 return html;
		        	 }
		        }
		};
		if(!CFnCharts.defaults.isShowScroll){
			options.xAxis = $.extend({},options.xAxis,{categories :CFnCharts.defaults.catagory});
		}
		//标题
		if(CFnCharts.defaults.title != ""&& CFnCharts.defaults.title != null){
			if(settings.modelType == "QX" || settings.modelType == "YB" || settings.modelType == "aq-AQI" 
				|| settings.modelType == "whyj-AQI" || settings.modelType == "whyj-AQIHS" || settings.modelType == "ZHFX"){
				options.title = {
						style : {
							color : '#131313',
							fontSize : '14px',
							fontWeight : '600',
							fontFamily: "微软雅黑"
						}
				};
			}else{
				options.title = {
						style : {
							color : '#666666',
							fontSize : '16px',
							fontWeight : 'bold'
						}
				};
			}
			
			if(typeof(CFnCharts.defaults.title) == "object"){
				options.title = $.extend(options.title,CFnCharts.defaults.title);
			}
			if(typeof(CFnCharts.defaults.title) == "string"){
				options.title.text = CFnCharts.defaults.title;
			}
		}else{
			options.title = {
					text : '',
			};
		}
		//副标题
		if(CFnCharts.defaults.subtitle !=""){
			options.subtitle = {
					style : {
						color : '#666666',
						fontSize : '12px',
						fontWeight : 'bold'
					}
			};
			if(typeof(CFnCharts.defaults.subtitle) == "object"){
				options.subtitle = $.extend(options.subtitle,CFnCharts.defaults.subtitle);
			}
			if(typeof(CFnCharts.defaults.subtitle) == "string"){
				options.subtitle.text = CFnCharts.defaults.subtitle;
			}
		}
		
		//x轴数据
		if(CFnCharts.defaults.xAxis){
			$.extend(options.xAxis,CFnCharts.defaults.xAxis);
		}
		
		//图例
		if(CFnCharts.defaults.legend){
			$.extend(options.legend,CFnCharts.defaults.legend);
		}
		
		//增加拖动轴
		if(CFnCharts.defaults.isShowScroll){
			options.navigator = {
							margin:5,
							height:15,
							outlineColor:CFnCharts.defaults.chartstyle.backgroundColor,
							//maskFill :CFnCharts.defaults.chartstyle.backgroundColor,
							series : {
								type: 'spline',
								fillOpacity : 0,
								color: CFnCharts.defaults.chartstyle.backgroundColor,
								lineWidth : 0,
							},
							xAxis : {
								gridLineWidth : 0,
								labels : {
									//enabled:false
								}
							}
			}
		}
		
		//把x轴时间换成毫秒的形式
		if(CFnCharts.defaults.modpSeries[0].type !="pie" && CFnCharts.defaults.isShowScroll){
			changeXData(CFnCharts.defaults);
		}
		
		//获取数据
		var data = parseData(CFnCharts.defaults);
		options.series = data.option;
		
		var plotOptions = {
            series: {
                dataLabels: {
                	allowOverlap : true,
                    enabled: (CFnCharts.defaults.enabledWay && CFnCharts.defaults.enabledWay == "none") ? false : true,
                },
                animation : false
            }
        };
		if(CFnCharts.defaults.enabledWay && CFnCharts.defaults.enabledWay == "minmax"){
			//获得需要展示数据曲线的x轴
			getShowLabelDataX(data.option);
			plotOptions = {
		            series: {
		                dataLabels: {
		                    enabled: true,
		                    allowOverlap : true,
		                    formatter : function(){
		                    	var seriencename = this.series.name;
		                    	var xserce = this.point.index;//通过索引
		                    	var showData = showLabelData[seriencename];
		                    	for(var j = 0;j<showData.length;j++){
		                    		if(showData[j] == xserce){
		                    			return this.y;
		                    		}
		                    	}
							}
		                },
		                animation : false
		            }
		        };
		}
		
		//可以设置柱子的宽度
		if(CFnCharts.defaults.pointWidth){
			var column = {
					pointWidth : CFnCharts.defaults.pointWidth
			}
			plotOptions.column = column;
		}
		if(settings.modelType == "QX" || settings.modelType == "aq-AQI"){
			plotOptions.areaspline = {fillOpacity : 0.0};
			if(data.yAxis.length == 1){
				data.yAxis[0].title.offset = 0;
				data.yAxis[0].title.y = -20;
				data.yAxis[0].title.x = 40;
			}else{
				data.yAxis[0].title.offset = 0;
				data.yAxis[1].title.offset = 0;
				data.yAxis[0].title.x = 40;
				data.yAxis[1].title.x = 40;
				data.yAxis[0].title.y = -20;
				data.yAxis[1].title.y = -20;
			}
		}
		options.plotOptions = plotOptions;
		if(settings.modelType == "AQI" || settings.modelType == "mai" || settings.modelType == "aq-AQI"){
			plotOptions.series.dataLabels.enabled = false;
		}
		if(settings.modelType == "QX" || settings.modelType == "YB"|| settings.modelType == "AQI" || settings.modelType == "mai"|| settings.modelType == "timeSequence"|| settings.modelType == "aq-AQI"){
			options.exporting = {enabled:false};
		}
		if(settings.modelType == "whyj-AQI" || settings.modelType == "whyj-AQIHS" || settings.modelType == "ZHFX"){
			plotOptions.series.dataLabels.enabled = false;
			options.tooltip = {enabled:false};
		}
		if(settings.modelType == "whyj-AQI"){
			plotOptions.areaspline = {
					fillColor:{
						linearGradient:[0,0,0,70],
						stops:[
						       [0,Highcharts.getOptions().colors[1]],
						       [1,Highcharts.Color(Highcharts.getOptions().colors[1]).setOpacity(0).get('rgba')]
						   ]
					},
					marker:{
						fillColor:"#fff",
						lineColor:"#3685CC",
						lineWidth:2
					},
					lineColor:"#3685CC"
			};
		}
		if(settings.modelType == "whyj-AQIHS"){
			plotOptions.areaspline = {
					fillColor:{
						linearGradient:[0,0,800,0],
						stops:[
						       [0,Highcharts.getOptions().colors[0]],
						       [1,Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
						   ]
					},
					marker:{
						fillColor:"#3786CC",
						lineColor:"#fff",
						lineWidth:2
					},
					lineColor:"#3786CC"
			};
		}
		if(settings.modelType == "timeSequence"){
			if(data.yAxis.length == 1){
				data.yAxis[0].title.offset = 0;
				data.yAxis[0].title.y = -10;
			}else{
				data.yAxis[0].title.offset = 0;
				data.yAxis[1].title.offset = 0;
				data.yAxis[0].title.y = -10;
				data.yAxis[1].title.y = -10;
			}
		}
		
		//获取y轴
		if(CFnCharts.defaults.modpSeries[0].type !="pie"){
			options.yAxis = data.yAxis;
		}
		
		//初始化图表
		//return new HighStock.StockChart(options);
		if(CFnCharts.defaults.modpSeries[0].type == "pie"){
			options.xAxis = null;
			options.tooltip = {
					 pointFormat: '{point.percentage:.1f}%</b>'
	        }
			options.plotOptions.pie = {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '{point.percentage:.1f} %',
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                    }
                }
            }
		}
	
		if(CFnCharts.defaults.isShowScroll){
			$('#'+settings.containId).highcharts('StockChart', options);
		}else{
			$('#'+settings.containId).highcharts(options);
		}
		return $('#'+settings.containId).highcharts();
	}
	
	//解析数据
	function parseData(data){
		//用户传过来的预报数据
		var datamodpSeries = data.modpSeries;
		//实况数据
		var databroadcastSeries = data.broadcastSeries && data.broadcastSeries.data ? data.broadcastSeries.data : [];
		
		//默认用实况数据替换掉预报数据
		var isReplaceYbData = data.isReplaceYbData == false ? data.isReplaceYbData : true;
		
		//解析x轴数据,转化为对应的毫秒形式
		
		var seriesYxis = {};
		var option = [];
		var yAxis = [];
		var yAxisCount = "";
		
		//得到最大值 和y轴间隔
		var max = {};
		//单轴走下面的判断   有yAxis 为双轴
		if(datamodpSeries[0].yAxis+"" == "undefined"){
			max  = getMax(datamodpSeries,databroadcastSeries,isReplaceYbData);
		}
		
		for(var i = 0;i<datamodpSeries.length;i++){
			
			//如果传过来风向，获得对应的图标
			if(datamodpSeries[i].data && datamodpSeries[i].data != "" && datamodpSeries[i].data[0].direction){
				for(var j = 0;j<datamodpSeries[i].data.length;j++){
					var singleData = datamodpSeries[i].data[j];
					if(!singleData.marker && singleData.direction && singleData.direction != '999999'){
						datamodpSeries[i].data[j] = $.extend({},datamodpSeries[i].data[j],{marker : setWindd(singleData.direction)});
					}
				}
			}
			
			var optionseries = {};
			optionseries = $.extend({},highstockdefault.series,datamodpSeries[i]);
			
			
			//若实况数据存在且实况数据替换预报数据
			var colors = [];//colors计算实况间隔，以便线显示不同的颜色
			if(isReplaceYbData && databroadcastSeries && databroadcastSeries.length >0){
				for(var j = 0;j<databroadcastSeries.length;j++){
					if(databroadcastSeries[j].y && databroadcastSeries[j].y != null){
						if(!databroadcastSeries[j].marker && databroadcastSeries[j].direction){
							databroadcastSeries[j] = $.extend({},databroadcastSeries[j],{marker : setWindd(databroadcastSeries[j].direction)});
						}
						optionseries.data[j] = $.extend({},optionseries.data[j],databroadcastSeries[j]);
					}
					if(databroadcastSeries[j].y == null){
						colors.push(j);
					}
				}
			}
			//根据数据的elementType获取对应的图表类型以及 y轴最大值、最小值相关的数据 
			var elementTypeData = parseYaxis(datamodpSeries[i].elementType);
			
			//图表类型  线不同的颜色
			var type = optionseries.type ? optionseries.type : elementTypeData.type;
			
			//线用不同的颜色 若存在实况，单实况是连续的，不存在null 
			var zones = [];
			if(isReplaceYbData && databroadcastSeries && databroadcastSeries.length >0 && type!="pie"){
				if(colors.length == 0){
					zones.push({value : databroadcastSeries[databroadcastSeries.length-1].x,color : databroadcastSeries[0].color});
				}else{
					if(colors.length == 1){
						if(colors[0] > 1){
							zones.push({value : databroadcastSeries[colors[0]-1].x,color : databroadcastSeries[0].color});
						}
					}else{
						for(var j = 1;j<colors.length-1;j++){
							if(colors[j]-colors[j-1] >2){ 
								//存在连续点
								zones.push({value : databroadcastSeries[colors[j-1]].x,color : databroadcastSeries[0].color}); 
							}else{
								zones.push({value : databroadcastSeries[colors[j]].x,color : datamodpSeries[i].color}); 
							}
									
						}
					}
					
					//实况最后一个空值的位置是否在倒数第三
					if(databroadcastSeries.length - colors[colors.length-1] > 2){
						zones.push({value : databroadcastSeries[colors[colors.length-1]+1].x,color : datamodpSeries[i].color}); 
						zones.push({value : databroadcastSeries[databroadcastSeries.length-1].x,color : databroadcastSeries[0].color}); 
					}
				}
				//预报用对应线的颜色  color : datamodpSeries[i].color
				zones.push({value : optionseries.data[optionseries.data.length-1].x});
			}
			var tooltip = {
					valueSuffix : elementTypeData.unit
			}
			
			optionseries = $.extend({},optionseries,{tooltip : tooltip,type : type,zoneAxis:'x',zones : zones,zIndex:(elementTypeData.type == "spline" ? 1:null)});
			
			//设置饼图的样式
			/*if(type == "pie"){
				optionseries = $.extend({},optionseries,{center:[100,50],size:150,showInLegend:false,dataLabels:{enabled:false}},optionseries.pieStyle);
			}*/
			
			//如果开发人员未传过来yAxis，自动拼Axis
			if(data.yAxis == null && type !="pie"){
				if(yAxisCount.indexOf(datamodpSeries[i].yAxis) < 0){
					yAxisCount += datamodpSeries[i].yAxis +",";
					var opposite = false;
					if((datamodpSeries[i].yAxis)%2 == 1){
						opposite = true;
					}
					var maxValue = datamodpSeries[i].max ? (datamodpSeries[i].max > elementTypeData.max ? elementTypeData.max : datamodpSeries[i].max): elementTypeData.max;
					if(max.maxVal < maxValue){
						maxValue = max.maxVal;
					}
					var yData = {
							showLastLabel : true,
							opposite : opposite,//若为奇数，轴在对面
							gridLineColor : '#B2C2DB',
							gridLineDashStyle : 'Dot',
							min : datamodpSeries[i].min ? datamodpSeries[i].min : elementTypeData.min,
							max : maxValue,
							tickInterval : max.tickInterval,
							title :{
								align : 'high',
								text : (datamodpSeries[i].unit ? datamodpSeries[i].unit : elementTypeData.unit),
								rotation : 0,
								style : {
									color : '#7CAEEE'
								}
							} 
						};
					yAxis.push(yData);
				}
			}
			option.push(optionseries);
		}
		//开发人员传过来Axis
		if(yAxis.length == 1){
			yAxis[0] = $.extend({},yAxis[0],{lineWidth : 1,lineColor : '#AFBFD7'});
		}
		if(data.modelType == "QX"){
			yAxis[0].labels = {style:{"color":"#42B7A5"}};
			yAxis[1].labels = {style:{"color":"#EE9C74"}};
		}else if(data.modelType == "AQI"){
			for(var i=0;i<option.length;i++){
				for(var j=0;j<option[i].data.length;j++){
					if(option[i].data[j].y == -1){
						option[i].data[j].y = null;
					}else{
						option[i].data[j].y = option[i].data[j].y;
					}
				}
			}
		}
		
		//若实况不替换预报数据
		if(!isReplaceYbData && databroadcastSeries && databroadcastSeries.length >0){
			option.push(data.broadcastSeries);
		}
		seriesYxis.option = option;
		seriesYxis.yAxis = yAxis;
		return seriesYxis;
	}
	
	//数据x轴换成毫秒形式和去掉没有用 的数据
	function changeXData(){
		var catagory = CFnCharts.defaults.catagory;
		if(CFnCharts.defaults.broadcastSeries && CFnCharts.defaults.broadcastSeries.data){
			for(var i = 0;i<CFnCharts.defaults.broadcastSeries.data.length;i++){
				CFnCharts.defaults.broadcastSeries.data[i].x = new Date(catagory[i]).getTime();
				CFnCharts.defaults.broadcastSeries.data[i].y == '999999' ? null : CFnCharts.defaults.broadcastSeries.data[i].y;
			}
		}
		for(var j = 0;j<CFnCharts.defaults.modpSeries.length;j++){
			for(var z = 0;z<CFnCharts.defaults.modpSeries[j].data.length;z++){
				CFnCharts.defaults.modpSeries[j].data[z].x = new Date(catagory[z]).getTime();
				CFnCharts.defaults.modpSeries[j].data[z].y == '999999' ? null : CFnCharts.defaults.modpSeries[j].data[z].y;
			}
		}
	}
	
	//解析y轴
	function parseYaxis(elementType){
		for(var i = 0;i< elementTypeData.length;i++){
			if(elementTypeData[i].elementType == elementType){
				return elementTypeData[i];
				break;
			}
		}
		
	}
	
	//计算所有数据的最大值  最小值 以及tickInterval   参数：预报数据 实况数据  是否用实况数据替换预报数据 
	function getMax(datamodpSeries,databroadcastSeries,isReplaceYbData){
		var totalData0Axis = [];
		var currentSeriesCount = datamodpSeries.length;
		//若实况存在，且替换
		if(isReplaceYbData && databroadcastSeries.length > 0){
			for(var i = 0;i < databroadcastSeries.length;i++){
				if(databroadcastSeries[i].y && databroadcastSeries[i].y != null){
					for(var j = 0;j< datamodpSeries.length;j++){
						datamodpSeries[j].data[i] = $.extend({},datamodpSeries[j].data[i],databroadcastSeries[i].y);
					}
				}
			}
		}
		
		//计算对应的最大值和tickInterval
		for(var z = 0;z<datamodpSeries.length;z++){
			var ybData = datamodpSeries[z].data;
			for(var s = 0 ;s<ybData.length;s++){
				if(ybData[s].y !='999999'){
					totalData0Axis.push(ybData[s].y);
				}
			}
			
		}
		//若实况不替换
		if(!isReplaceYbData){
			currentSeriesCount ++;
			for(var d = 0;d < databroadcastSeries.length;d++){
				if(databroadcastSeries[d].y !='999999'){
					totalData0Axis.push(databroadcastSeries[d].y);
				}
			}
		}
		
		var returnObj = $.extend(getInterval(totalData0Axis,currentSeriesCount),{yAxis : 0})
		return returnObj;
	}
	
	function getInterval(totalData,count){
		//从小到大排序
		if(totalData.length > 0 && count > 4){
			totalData.sort(function(a,b){return a-b;});
			var maxVal = totalData[totalData.length-1];
			var tickInterval = maxVal/count/5 < 1 ? Number((maxVal/5).toFixed(1)) : Math.ceil(maxVal/count/5)*5;
			var returnObj = {
					maxVal : Math.ceil(maxVal/5)*5,
					tickInterval : tickInterval
			};
			
			return returnObj;
		}
	}
	
	//获取线的最大值和最小值对应的x轴
	function getShowLabelDataX(SeriesData){
		showLabelData = {};
		if(!SeriesData && !SeriesData instanceof Array){
			return;
		}
		for(var i = 0; i<SeriesData.length;i++){
			var incredeed = true;//是否递增
			var SeriesSingleData = SeriesData[i].data;
			if(SeriesSingleData.length >2){
				incredeed = (SeriesSingleData[1].y - SeriesSingleData[0].y > 0)? true : false;
			}
			var series = [];
			//获取最小值，最大值对应的x轴
			for(var j = 1;j<SeriesSingleData.length-1;j++){
				if(SeriesSingleData[j+1].y- SeriesSingleData[j].y > 0){
					if(!incredeed){
						series.push(j);
					}
					incredeed = true;
				}else{
					if(incredeed){
						series.push(j);
					}
					incredeed = false;
				}
			}
			showLabelData[SeriesData[i].name] = series;
		}
	}
	
	//设置风向
	function setWindd(windd) {
		var weather;
		var marker = {symbol:'circle'};
		if (windd == '西') {
			weather = 'W.png';
		} else if (windd == '东') {
			weather = 'E.png';
		} else if (windd == '北') {
			weather = 'N.png';
		} else if (windd == '南') {
			weather = 'S.png';
		} else if (windd == '西北') {
			weather = 'NW.png';
		} else if (windd == '西南') {
			weather = 'SW.png';
		} else if (windd == '东北') {
			weather = 'NE.png';
		} else if (windd == '东南') {
			weather = 'ES.png';
		} else if (windd == '南西南') {
			weather = 'SSW.png';
		} else if (windd == '西西南') {
			weather = 'WSW.png';
		} else if (windd == '西西北') {
			weather = 'WNW.png';
		} else if (windd == '北西北') {
			weather = 'NNW.png';
		} else if (windd == '北东北') {
			weather = 'NNE.png';
		} else if (windd == '东东北') {
			weather = 'ENE.png';
		} else if (windd == '东东南') {
			weather = 'ESE.png';
		} else if (windd == '南东南') {
			weather = 'SSE.png';
		}else if (windd == '静风') {
			weather = 'SILENCE.png';
		}
		if (weather) {
			marker.symbol = 'url(../static/widgets/cafejs/script/nChart/windd/' + weather + ')';
		}
		
		return marker;
	}
	
	function exportPic(type){
		//前台导出
		/*var charId = CFnCharts.defaults.chartstyle.renderTo;
		var that = this;
		var canvas = document.createElement("canvas");
		var fileName = CFnCharts.defaults.exportName;
		canvas.width = $("#"+charId).width();
		canvas.height = $("#"+charId).height();
		var ct = canvas.getContext("2d");
		ct.fillStyle = "#FFF";
		ct.fillRect(0,0,canvas.width,canvas.height);
		//调整保存区域的上部和左部位置
		var top = 0;
		var left =0;
		var svg = document.createElement("canvas");
		svg.id = "canvas-svg";
		svg.width = $("#"+charId).width();
		svg.height = $("#"+charId).height();
		
		$("#"+charId).append($(svg).hide());
		var svghtm='';
		svghtm = that.getSVG();
		var $input = '<input type="hidden" id="hidenHighCode"/>';
		$("#"+charId).append($input)
		$input.val(data);
		svghtm = 
		$("#"+charId).find('svg').each(function(i,elem){
			svghtm+=elem.outerHTML;
		});
		var saveFile = function(data,filename){
			var save_link = document.createElementNS('http://www.w3.org/1999/xhtml','a');
			save_link.href = data;
			save_link.download = filename;
			var ev =document.createEvent('HTMLEvents');
			ev.initEvent('click',false,true);
			save_link.dispatchEvent(ev); 
		};
		canvg("canvas-svg",svghtm,{'renderCallback':function(){
			$("#canvas-svg").remove();
			ct.drawImage(svg, left, top);
			var $div = $('<div style="display:transparent;">').append(canvas);
			$("#"+charId).append($div.hide());
			var imgData = canvas.toDataURL("image/png");
			imgData = imgData.replace('image/png','image/octet-stream');
			saveFile(imgData,fileName+'.'+type);
			$div.remove();
		}});*/
	}
	
	//图表自适应
	function bindEvent(containId,chart){
		$("#"+containId).resize(function(){
			chart.reflow();
		});
	}
	
	var CFnCharts = function(settings){
		if(!settings.containId || !settings.modpSeries || settings.modpSeries.length == 0){
			return;
		}
		this.chart = initChart(settings);
		chartObj = this.chart;
		bindEvent(settings.containId,this.chart);
		var exportings ={
				enabled: true,
				buttons:{
					contextButton:{
						 menuItems:[
						            {
						            	text:'下载PNG图片',
						            	onclick : function(){
						            		exportPic("png");
						            	}
						            	
						            },
						            {
						            	text:'下载JPEG图片',
						            	onclick : function(){
						            		exportPic("jpeg");
						            	}
						            	
						            }
						            ]
					}
				},
			};
		if(settings.exporting){
			exportings = $.extend({},exportings,settings.exporting);
		}
		try{
			this.chart.update({
				exporting : exportings
			});
		}catch(error){
			
		}
	};
	CFnCharts.defaults = {
			containId :'',
			catagory : [],//x轴数据
			enabledWay :'all',
			modpSeries : [],//预报数据
			broadcastSeries :{},//实况数据
			isReplaceYbData :true,//是否用预报数据替换实况数据
			title :null,
			subtitle :null,
			xText:'时间<br>日期',
			exportName : '导出图片',
			chartstyle :{//图表的样式
				inverted : false,//图表 x ,y轴是否调换
				backgroundColor : ((Highcharts.theme && Highcharts.theme.chart.backgroundColor) || '#ffffff'),
				defaultSeriesType : 'spline',
				alignTicks : true,
				type: 'spline',
				animation : false,
				borderColor : '#4572A7',
				borderRadius :0,
				borderWidth : 0,
				className : null,
				width : null,
				height : null,
				//margin : [10,10,10,10],
				shadow : false,
				style : {"fontFamily":"\"Lucida Grande\", \"Lucida Sans Unicode\", Verdana, Arial, Helvetica, sans-serif","fontSize":"12px"}
			},
			legend :{},//图例
			yAxis :null,
			pointWidth : null,
			isShowScroll :true//是否显示拖拽
	};
	CFnCharts.prototype = {
			//增加数据 以数组的形式
			addSeriesData : function(seriesArray){
				var that = this;
				var obj = {
						type : 'spline',
						name : '增加数据'
				};
				if(seriesArray && (seriesArray instanceof Array || seriesArray instanceof Object)){
					if(seriesArray instanceof Array){
						for(var i = 0;i<seriesArray.length;i++){
							var temp = $.extend({},obj,seriesArray[i]);
							if(temp.data && temp.data.length > 0){
								if(CFnCharts.defaults.isShowScroll){
									for(var y = 0;y<temp.data.length;y++){
										temp.data[y].x = that.chart.series[0].data[y].x;
									}
								}
								
								that.chart.addSeries(temp,true);
							}
						}
					}else{
						if(seriesArray.data && seriesArray.data.length > 0){
							if(CFnCharts.defaults.isShowScroll){
								for(var i = 0;i<seriesArray.data.length;i++){
									seriesArray.data[i].x = that.chart.series[0].data[i].x;
								}
							}
							that.chart.addSeries(seriesArray,true);
						}
					}
				}else{
					return;
				}
			}
	};
	CafeJS.nCharts = function(settings){
		if(settings && (settings instanceof Array || settings instanceof Object)){
			if(settings instanceof Array){
				var cfhighchartsArray = [];
				for(var i = 0;i<settings.length;i++){
					var cfhighcharts =new CFnCharts(settings[i]);
					cfhighchartsArray.push(cfhighcharts);
				}
				return cfhighchartsArray;
			}else{
				var cfhighcharts =new CFnCharts(settings);
				return cfhighcharts;
			}
		}
	};
});